<?php

App::uses('Certification', 'Model');
App::uses('UserLine', 'Model');
App::uses('Test', 'Model');
App::uses('Crud', 'Model');
App::uses('Evaluation', 'Model');

class Categorization extends Crud
{
    /** Al Agregar/eliminar/actualizar las constantes de los modelos implica ir
     * y actualizar los comentarios en los campos de la tabla asociada a este modelo.
     */
    const STATUS_ENABLED = 1;
    const STATUS_DISABLED = 0;
    const REQUIERES_APROVAL = 1;
    const NO_REQUIERES_APROVAL = 0;

    public function getEnabledByLine($lineId)
    {
        $filters = array(
            'fields' => array(
                'id',
                'test_id',
                'line_id',
                'name',
                'certifications',
                'colour',
                'icon',
                'lower_limit',
                'requires_approval',
            ),
            'joins' => array(
                array(
                    'table' => 'tests',
                    'alias' => 't',
                    'type' => 'LEFT',
                    'conditions' => array(
                        't.id = Categorization.test_id',
                        't.status' => Test::STATUS_ENABLED,
                    ),
                ),
            ),
            'conditions' => array(
                'Categorization.status' => self::STATUS_ENABLED,
                'Categorization.line_id' => $lineId,
            ),
            'order' => array(
                'Categorization.orden' => 'ASC',
                //'Categorization.creation_date' => 'ASC',
            ),
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    /**
     * Obtenemos la siguiente categoria en base a una categoria que se recibe
     * como referencia
     * @param string $categorizationId Categoria de referencia apartir de la cual
     * se calcula la siguiente categoria de rango superior.
     * @return array
     */
    public function getNext($userId, $categorizationId)
    {
        $filters = array(
            'fields' => array(
                'cat.name',
                'cat.icon',
                'cat.colour',
                'cat.certifications',
                'cat.lower_limit',
                'cat.requires_approval',
                't.id',
                't.name',
                'IFNULL(e.success,0) as evaluationSuccess'
            ),
            'joins' => array(
                array(
                    'table' => 'categorizations',
                    'alias' => 'cat',
                    'type' => 'INNER',
                    'conditions' => array(
                        'cat.line_id = Categorization.line_id',
                        'cat.status' => self::STATUS_ENABLED,
                        'cat.certifications > Categorization.certifications',
                    ),
                ),
                array(
                    'table' => 'tests',
                    'alias' => 't',
                    'type' => 'LEFT',
                    'conditions' => array(
                        't.id = cat.test_id',
                        't.status' => Test::STATUS_ENABLED,
                    ),
                ),
                array(
                    'table' => 'evaluations',
                    'alias' => 'e',
                    'type' => 'LEFT',
                    'conditions' => array(
                        'e.user_id' => $userId,
                        'e.test_id = t.id',
                        'e.status' => Evaluation::STATUS_ENABLED,
                    ),
                ),
            ),
            'order' => array(
                'Categorization.certifications' => 'DESC',
                'Categorization.creation_date' => 'DESC',
            ),
            'conditions' => array(
                'Categorization.id' => $categorizationId,
            ),
        );
        $record = $this->find('first', $filters);
        return Hash::flatten($record);
    }

//    public function getLowLevelByLine($lineId) {
//        $filters = array(
//            'fields' => array(
//                'id',
//            ),
//            'conditions' => array(
//                'status' => self::STATUS_ENABLED,
//                'line_id' => $lineId,
//            ),
//            'order' => array(
//                'orden' => 'ASC'
//            ),
//        );
//        $record = $this->find('first', $filters);
//        return $record['id'];
//    }

    /**
     * Marcamos todas las categorias de una linea como que no son objetivos.
     * @param string $lineId UUID
     */
    public function clearIsObjetiveByLine($lineId)
    {
        $fields = array(
            'is_objetive' => self::NO_OBJETIVE,
        );
        $conditions = array(
            'line_id' => $lineId,
        );
        $this->updateAll($fields, $conditions);
    }

    /**
     * Buscamos si existe una categoria objetivo para una linea
     * @param string $lineId UUID
     * @return boolean
     */
    public function hasObjetiveByLine($lineId)
    {
        $filters = array(
            'conditions' => array(
                'status' => self::STATUS_ENABLED,
                'is_objetive' => self::IS_OBJETIVE,
                'line_id' => $lineId,
            ),
        );
        $records = $this->find($filters);
        return empty($records);
    }

    public function getHighCategory($lineId)
    {
        $filters = array(
            'fields' => array(
                'id',
            ),
            'conditions' => array(
                'status' => self::STATUS_ENABLED,
                'line_id' => $lineId,
            ),
            'order' => array(
                'Categorization.certifications' => 'DESC',
                'Categorization.creation_date' => 'DESC',
            ),
        );
        $record = $this->find('first', $filters);
        return $record;
    }

    public function getCategorizationForPassport($lineId, $payroll)
    {
        $filters = array(
            'fields' => array(
                'Categorization.icon as icon',
                'Categorization.colour as color',
            ),
            'joins' => array(
                array(
                    'table' => 'us3rs_r4gg14n4',
                    'alias' => 'us',
                    'type' => 'inner',
                    'conditions' => array('us.nomina' => $payroll)
                ),
                array(
                    'table' => 'user_lines',
                    'alias' => 'ul',
                    'type' => 'inner',
                    'conditions' => array('ul.user_id = us.id', 'ul.line_id' => $lineId)
                )
            ),
            'conditions' => array(
                'Categorization.id = ul.level',
            )
        );
        return $this->flatArray($this->find('all', $filters));
    }

    /**
     * Obtenemos los niveles de categorizacion menores al nivel pasado como referencia
     * @param $levelName Nombre del nivel de referencia
     * @param $lineId Id de la linea
     * @return array Arreglo con los niveles inferiores al nivel de referencia
     */
    public function getLowLevels($levelName, $lineId)
    {
        $filters = array(
            'fields' => array(
                'c.id',
            ),
            'joins' => array(
                array(
                    'table' => 'categorizations',
                    'alias' => 'c',
                    'type' => 'inner',
                    'conditions' => array(
                        'c.line_id = Categorization.line_id',
                        'c.status' => self::STATUS_ENABLED,
                        'c.orden < Categorization.orden',
                    ),
                ),
            ),
            'conditions' => array(
                'Categorization.name' => $levelName,
                'Categorization.line_id' => $lineId,
            )
        );
        return $this->flatArray($this->find('all', $filters));
    }
}
